package com.yaozheng.vocationaltraining.service.impl;

import android.text.TextUtils;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.yaozheng.vocationaltraining.iview.BaseView;
import com.yaozheng.vocationaltraining.iview.IAddQuestionsView;
import com.yaozheng.vocationaltraining.iview.IHundredQuestionsEncyclopediaView;
import com.yaozheng.vocationaltraining.service.AddQuestionsService;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.ImageUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.utils.http.okhttp.OkHttpClientManager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EBean;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by moon on 2017/11/10.
 */

@EBean
public class AddQuestionsServiceImpl implements AddQuestionsService {
    IAddQuestionsView iTokenBaseView;

    @Override
    public void init(IAddQuestionsView iTokenBaseView) {
        this.iTokenBaseView = iTokenBaseView;
    }

    @Background
    @Override
    public void loadRewardData() {
        try {
            OkHttpClientManager
                    .getInstance()
                    .get(Constants.ROOTURL + "/knowledge/awards",
                            iTokenBaseView.getToken(), new BaseView(iTokenBaseView) {
                                @Override
                                public void responseSuccess(JSONObject jsonObject) {
                                    iTokenBaseView.rewardDataSuccess(jsonObject);
                                }

                                @Override
                                public void responseError(String error) {
                                    iTokenBaseView.rewardDataError(error);
                                }
                            });
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
            if (iTokenBaseView.isResponseResult()) {
                iTokenBaseView
                        .rewardDataError(ErrorUtils.SERVER_CONNECTION_ERROR);
            }

        }
    }

    @Background
    @Override
    public void loadCategories() {
        try {
            OkHttpClientManager
                    .getInstance()
                    .get(Constants.ROOTURL + "/knowledge/categories",
                            iTokenBaseView.getToken(), new BaseView(iTokenBaseView) {
                                @Override
                                public void responseSuccess(JSONObject jsonObject) {
                                    iTokenBaseView.categoriesListSuccess(jsonObject);
                                }

                                @Override
                                public void responseError(String error) {
                                    iTokenBaseView.categoriesListError(error);
                                }
                            });
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
            if (iTokenBaseView.isResponseResult()) {
                iTokenBaseView
                        .categoriesListError(ErrorUtils.SERVER_CONNECTION_ERROR);
            }

        }
    }

    @Background
    @Override
    public void addQuestion(final int cateId, final String title, String image,final String body,final String rewardNum) {
        try {
            if (!TextUtils.isEmpty(image)) {
                byte[] uploadContent = ImageUtils.bitmap2Bytes(ImageUtils
                        .revitionImageSize(image));
                if (uploadContent == null) {
                    iTokenBaseView.addQuestionError("上传图片失败！！！");
                }
                OkHttpClientManager.getInstance().upload(
                        Constants.ROOTURL + "/knowledge/image/add",
                        iTokenBaseView.getToken(),
                        new OkHttpClientManager.IBaseViewCallback(new BaseView(iTokenBaseView) {
                            @Override
                            public void responseSuccess(JSONObject jsonObject) {
                                JSONObject imageObject = TypeUtils.getJsonObject(jsonObject, "data");

                                addQuestionByImageUrl(cateId,title,
                                        imageObject.getString("image"),body,rewardNum);
                            }

                            @Override
                            public void responseError(String error) {
                                iTokenBaseView.addQuestionError(error);
                            }

                            @Override
                            public boolean isResponseResult() {
                                return iTokenBaseView.isResponseResult();
                            }

                        }), uploadContent);
            }else{
                addQuestionByImageUrl(cateId,title,
                        "",body,rewardNum);

            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
            if (iTokenBaseView.isResponseResult()) {
                iTokenBaseView.addQuestionError("发布问题失败");
            }

        }

   }

   @Background
    @Override
    public void loadScore() {
       try {
           OkHttpClientManager
                   .getInstance()
                   .get(Constants.ROOTURL + "/user/score",
                           iTokenBaseView.getToken(), new BaseView(iTokenBaseView) {
                               @Override
                               public void responseSuccess(JSONObject jsonObject) {
                                   iTokenBaseView.loadScoreSuccess(jsonObject);
                               }

                               @Override
                               public void responseError(String error) {
                                   iTokenBaseView.loadScoreError(error);
                               }
                           });
       } catch (Exception e) {
           ErrorUtils.outErrorLog(e);
           if (iTokenBaseView.isResponseResult()) {
               iTokenBaseView
                       .loadScoreError(ErrorUtils.SERVER_CONNECTION_ERROR);
           }

       }
    }

    public void addQuestionByImageUrl(int cateId, String title, String image, String body, String rewardNum) {
        try {
            HashMap<String, String> para = new HashMap<String, String>();
            para.put("cateId", cateId+"");
            para.put("title", title);
            para.put("body", body);
            if (!TextUtils.isEmpty(image)){
//                ["http://api.borgwardapp.com/app/question/2017/10/fb0184a7c8cc2a2d2f76e7000b8b0f9a.jpg"]
                para.put("images","['"+image+"']");
            }
            para.put("score",rewardNum);

            JSONObject json = new JSONObject();
            json.put("cateId", cateId+"");
            json.put("title", title);
            json.put("body", body);
            json.put("score",rewardNum);

            if (!TextUtils.isEmpty(image)){
//                ["http://api.borgwardapp.com/app/question/2017/10/fb0184a7c8cc2a2d2f76e7000b8b0f9a.jpg"]
                para.put("images",image);
                JSONArray array = new JSONArray();
                array.add(image);
                json.put("images",array);
            }

            OkHttpClientManager.getInstance().postJson(
                    Constants.ROOTURL + "/knowledge/question/add",
                    iTokenBaseView.getToken(), json.toString(), new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    iTokenBaseView.addQuestionError("发布问题失败");
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    iTokenBaseView.addQuestionSuccess(null);
                }
            });
//            OkHttpClientManager.getInstance().post(
//                    Constants.ROOTURL + "/knowledge/question/add", iTokenBaseView.getToken(), para, new BaseView(iTokenBaseView) {
//                        @Override
//                        public void responseSuccess(JSONObject jsonObject) {
//                            iTokenBaseView.addQuestionSuccess(jsonObject);
//                        }
//
//                        @Override
//                        public void responseError(String error) {
//                            iTokenBaseView.addQuestionError(error);
//                        }
//                    });
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
            if (iTokenBaseView.isResponseResult()) {
                iTokenBaseView
                        .addQuestionError(ErrorUtils.SERVER_CONNECTION_ERROR);
            }

        }
    }


}
